package 文件小程序;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:扫描指定目录,找到带有关键字的文件,然后进行删除
 * User: lenovo
 * Date: 2022-10-17
 * Time: 9:08
 */
public class demo1 {
    public static void main(String[] args) throws IOException {
        //1.输入根文件名
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入根目录:");
        String rootDirPath = scanner.next();
        System.out.println("请输入你要查找的文件名:");
        String toDelete = scanner.next();
        File rootDir = new File(rootDirPath);
        //判断是否为文件夹
        if(!rootDir.isDirectory()){
            System.out.println("未找到该目录");
            return;
        }
        //代码走到这里说明是目录,并且要对这个目录进行递归遍历(n叉树)
        //rets用来存放toDelete文件
        List<File> rets = new ArrayList<>();
        scan(rootDir,toDelete,rets);
        System.out.println("找到了包含"+toDelete+"共"+rets.size()+"份文件:");
        for (File file1:rets) {
            System.out.println(file1.getCanonicalPath()+"是否删除(y/n)");
            String in = scanner.next();
            if(in.toLowerCase().equals("y")){
                file1.delete();
            }

        }


    }
//递归遍历
    private static void scan(File rootDir, String toDelete, List<File> rets) throws IOException {
        System.out.println("当前位置:"+rootDir.getCanonicalPath());
        //遍历根目录
        File[] files =rootDir.listFiles();
        if(files.length ==0 || files == null){
            return;
        }
        for (File file: files) {
            //还是目录,继续遍历
            if(file.isDirectory()){
                scan(file,toDelete,rets);
            }else{//不是目录,是文件
                //如果文件里包含了toDelete,就把它的绝对路径添加到rets顺序表里
                if(file.getName().contains(toDelete)){
                    rets.add(file.getAbsoluteFile());
                }
            }
        }

    }
}
